#-*-coding:utf-8-*-
'''
This module is used to simulate the LZW algorith
'''
from myoperate import DictOperate

class LZ7W:
    '''
    to accomplish the compression
    '''
    def __init__(self):
        #self.golombcode = self.GolombEncode(2)
        pass

    def GolombEncode(self,m):
        '''
        the Golomb encoding,m is the parameter which decided the length and style of the code.
        '''
        if m > 0:
            b = 2 * m
            c = dict()
            for x in range(1,10):
                q = (x - 1) / b
                r = x - q*b - 1
                k = bin(r)[2:]
                if len(k) < m:
                    k = (m - len(k)) * '0' + k
                c[x] = q * '1' + '0' + k
            return c

        else:
            return False

    def GolombAutoMachine(self,m):
        '''
        the decode automachine.just like a binary tree.
        '''
        orderid = 1
        autodic = dict()
        for (i,j) in self.golombcode.items():
            nstat = 0
            for k in range(len(j)):
                if not autodic.has_key(nstat):
                    autodic[nstat] = dict()
                    autodic[nstat][j[k]] = orderid
                    nstat = orderid
                    orderid += 1        #record the status
                else:
                    if autodic[nstat].has_key(j[k]):
                        nstat = autodic[nstat][j[k]]
                    else:
                        autodic[nstat][j[k]] = orderid
                        nstat = orderid
                        orderid += 1
            else:
                autodic[nstat] = [-1,i,0]       #end status
                #orderid += 1
        return autodic



    def GolombDecode(self,m):
        '''
        Decode the Golomb
        '''
        pass

    def testGolomb(self):
        '''
        test Golomb.
        '''
        self.golombcode = self.GolombEncode(2)
        print self.golombcode
        print self.GolombAutoMachine(2)

if __name__ == '__main__':
    c = LZ7W()
    c.testGolomb()

